<?php
/**
 * Created by PhpStorm.
 * User: sxg
 * Date: 2023/7/11
 * Time: 8:46
 */

use Socket\Ms\Protocols\MqttClient;

require_once "vendor/autoload.php";

$client = new \Socket\Ms\Client("mqtt://127.0.0.1:9501");
$client->mqttSettings['clientIdentifier'] = 'xcmgec';
$client->mqttSettings['user_name'] = 'sxg';
$client->mqttSettings['password'] = '123456';
$client->mqttSettings['keepalive'] = '30';

$client->on("open", function (\Socket\Ms\Client $client) {
    echo "Mqtt服务器连接成功\n";
    //连接成功后订阅主题
    $MqttObj = $client->_protocol;
    /**@var MqttClient $MqttObj */
    if ($subscribeFrame = $MqttObj->subscribe("led", '2')) {
        $client->sendDataForMqtt($subscribeFrame);
    }
//    $client->sendDataForMqtt($MqttObj->responsePUBLISHPACK("led", "hello, world", 2));
});

$client->on("subscribe_ack", function (\Socket\Ms\Client $client) {
    echo "订阅主题成功\n";
//    $MqttObj = $client->_protocol;
//    /**@var MqttClient $MqttObj */
//    $unsubscribePack = $MqttObj->unsubscribe('led');
//    $client->sendDataForMqtt($unsubscribePack);
});


$client->on("unsubscribe_ack", function (\Socket\Ms\Client $client) {
    echo "取消订阅主题成功\n";
});

$client->on("subscribe", function (\Socket\Ms\Client $client) {
    $MqttObj = $client->_protocol;
    /**@var MqttClient $MqttObj */
    echo "接收到服务端转发的消息:".$MqttObj->publishPacketMessage.PHP_EOL;
    $client->sendDataForMqtt($MqttObj->responsePUBLISHPACK("led", "hello, world", 2));
});

$client->start();
$client->loop();
